const router = require('express').Router()
const {db,jwtRouter} = require('../util')

router.get('/topn', (req,res)=>{
    let cat_id = req.query.cat_id || 0
    if(cat_id == 0) {
        let sql = `SELECT c.username,COUNT(*) integral
                     FROM ti_user_questions a
                     LEFT JOIN ti_questions b ON a.question_id=b.id
                     LEFT JOIN ti_users c ON a.user_id=c.id
                      WHERE a.isright=1
                       GROUP BY a.user_id
                        ORDER BY integral DESC
                         LIMIT 100`
        db.query(sql, (err,results)=>{
            res.json({
                ok: 1,
                data: results
            })
        })
    } else {
        let sql = `SELECT c.username,COUNT(*) integral
                    FROM ti_user_questions a
                    LEFT JOIN ti_questions b ON a.question_id=b.id
                    LEFT JOIN ti_users c ON a.user_id=c.id
                     WHERE b.category_id = ? AND a.isright=1
                      GROUP BY a.user_id
                       ORDER BY integral DESC
                        LIMIT 100`
        db.query(sql, cat_id, (err,results)=>{
            res.json({
                ok: 1,
                data: results
            })
        })
    }
})

jwtRouter.post('/:id(\\d+)/:answer([0123])', (req,res)=>{
    let sql = 'SELECT `right` FROM ti_questions WHERE id=?'
    db.query(sql, req.params.id, (err,results)=>{
        if(results[0]) {
            sql = 'REPLACE INTO ti_user_questions SET ?'
            let data = {
                user_id: req.user.id,
                question_id: req.params.id,
                answer: req.params.answer,
                isright: Number(results[0].right == req.params.answer)
            }
            db.query(sql, data, (err,results)=>{
                res.json({
                    ok: 1
                })
            })
        } else {
            res.json({
                ok: 0,
                error: '题目不存在'
            })
        }
        
    }) 
})
module.exports = [router,jwtRouter]